﻿#include "ssSocketSelect.h"
#include <cstdio>

namespace StarSeeker
{

ssSocketSelect::ssSocketSelect()
{
	m_timeout.tv_sec = 0;
	m_timeout.tv_usec = 0;
	m_frameTime = 0;
	m_enable = false;
	m_nfds = 0;
	m_isBlock = false;
}

ssSocketSelect::ssSocketSelect(int sec, int usec)
{
	m_timeout.tv_sec = sec;
	m_timeout.tv_usec = usec;
	m_frameTime = 0;
	m_enable = false;
	m_nfds = 0;
	m_isBlock = false;
}

ssSocketSelect::~ssSocketSelect()
{
}

bool ssSocketSelect::RunFrame(unsigned int ms)
{
	m_frameTime = ms;

	if (m_enable)
	{
		int	rc;
		int err=0;

		BeforeFDSET();

		timeval tmv = m_timeout;
#ifdef SS_USE_WINDOWS
        rc = select(0, &m_fdRead, &m_fdWrite, &m_fdExcept, m_isBlock?0:&tmv);
        if ( SOCKET_ERROR==rc )
        {
            err = GetSocketError();
            printf("select failed,error code:%d\n", err);
            return false;
        }
        //else if ( 0==rc )
        //{
        //	//timeout
        //}
        else
        {
            ProcessFDSET();
        }
#else
        rc = select(m_nfds, &m_fdRead, &m_fdWrite, &m_fdExcept, m_isBlock?0:&tmv);
        if ( -1==rc )
        {
            err = GetSocketError();
            printf("select failed,error code:%d\n", err);
            return false;
        }
        else
        {
            ProcessFDSET();
        }
#endif
		AfterFDSET();
		return true;
    }
	return false;
}

void ssSocketSelect::SetBlock(bool isBlock)
{
	m_isBlock = isBlock;
}

}
